<?php

namespace app\admin\model\yungift;


use think\Db;

/**
 * 礼品 - 规格
 */
class GiftSpec extends \addons\yungift\model\GiftSpec
{
    // 自定义初始化
    protected static function init()
    {
        // 新增、更新规格
        GiftSpec::event('after_write', function ($record) {
            $scenario = $record->data['scenario'] ?? null;
            if ($scenario === 'batch') {  // 礼品修改规格，同步规格库存
                if ($record->data['type'] == GiftSpec::TYPE_2) {
                    Db::transaction(function () use ($record) {
                        GiftSpec::where(['id' => $record->id])->lock(true)->find();  // 锁住规格库存
                        $countLeft = GiftCode::where([
                            'gift_spec_id' => $record->id,
                            'status'       => GiftCode::STATUS_NORMAL
                        ])->count();
                        GiftSpec::update([
                            'count_left' => $countLeft,
                            'gift_id'    => $record->gift_id,
                            'scenario'   => 'sync'
                        ], ['id' => $record->id], true);
                    });
                } else {
                    Db::transaction(function () use ($record) {
                        GiftMain::where(['id' => $record->gift_id])->lock(true)->find();  // 锁住礼品库存
                        $countLeft = GiftSpec::where(['gift_id' => $record->gift_id])->sum('count_left');
                        GiftMain::update(['count_left' => $countLeft], ['id' => $record->gift_id]);
                    });
                }
            } elseif ($scenario === 'sync') {  // 上面传递、券码变更，同步礼品库存
                if (array_key_exists('gift_id', $record->data)) {
                    Db::transaction(function () use ($record) {
                        GiftMain::where(['id' => $record->gift_id])->lock(true)->find();  // 锁住礼品库存
                        $countLeft = GiftSpec::where(['gift_id' => $record->gift_id])->sum('count_left');
                        GiftMain::update(['count_left' => $countLeft], ['id' => $record->gift_id]);
                    });
                }
            }

            return true;
        });
    }
}
